//app.js
require('./pollyfill/index');
const md5 = require('./utils/md5');
const {
  toast, confirm, showLoading, hideLoading, showAddressModal, formatDateTime, isPhoneAvailable
} = require('./utils/util.js');
var arrEntities = { 'lt': '<', 'gt': '>', 'nbsp': ' ', 'amp': '&', 'quot': '"' };

App({
  onLaunch: function () {

    wx.login({
      success: res => {
        this.globalData.logincode = res.code;
        this.getToken();
      },
      fail: err => {
        hideLoading()
        this.dispatchError('登录失败，请检查网络连接')
      }
    })
  },
  globalData: {
    webUrl: 'https://www.the-bestme.com',
    address: {
      status: -1,
      value: null
    },
    coupon: {
      status: -1,
      value: null
    },
    returnStatus: {
      '-2': '用户取消',
      '-1': '审核不通过',
      '0': '待审核',
      '1': '通过',
      '2': '已发货',
      '3': '已完成'
    },
    statusDesc: {
      0: '仅退款',
      1: '退款退货',
      2: '换货'
    }
  },
  getToken: function () {
    return new Promise(resolve => {
      this.getUserWxInfo().then(() => { resolve() }).catch(err => {
        this.isAuthrized().then(yes => {
          if (yes) {
            toast.error(err)
          } else {
            wx.navigateTo({
              url: '/pages/auth/auth'
            })
          }
        })
      })
    });
  },
  toUserCenter: function () {
    wx.switchTab({
      url: '/pages/my/my',
    });
  },
  isAuthrized: function () {
    return new Promise(resolve => {
      wx.getSetting({
        success: (res) => {
          console.log(res.authSetting["scope.userInfo"]);
          if (res.authSetting["scope.userInfo"]) {
            resolve(true)
          } else {
            resolve(false)
          }
        },
        fail: () => {
          resolve(false)
        }
      })
    })
  },
  getUserWxInfo: function () {
    return new Promise((resolve, reject) => {
      if (this.globalData.userWxInfo) {
        this.getOpenid().then(res => {
          if (res == true) {
            resolve();
          }
        });
      } else {
        wx.getUserInfo({
          success: (res) => {
            this.globalData.userWxInfo = res.userInfo
            this.getOpenid().then(res => {
              if (res == true) {
                resolve();
              }
            });
          },
          fail: () => {
            reject('授权失败')
          }
        })
      }
    });
  },
  getOpenid: function () {
    return new Promise(resolve => {
      let url = '/index.php/api/user/XcxGetOpenid';
      let params = {
        code: this.globalData.logincode,
        userInfo: this.globalData.userWxInfo
      }
      this.request(url, params).then(res => {
        if (res.status === 'ok') {
          this.globalData.uid = res.result.uid;
          this.globalData.token = md5.hexMD5(res.result.uid + res.result.ukey);
          this.globalData.shareTitle = res.result.conf.store_title;
          this.globalData.shareImgUrl = this.globalData.webUrl + res.result.conf.store_user_logo;
          this.globalData.nickName = res.result.nickName;
          this.dispatchReady();
          resolve(true);
        }
        else {
          resolve(false);
        }
      });
    });
  },
  request: function (url, params = {}, method = 'POST') {
    return new Promise((resolve, reject) => {
      let headers = {
        "Content-Type": "application/x-www-form-urlencoded"
      }
      if (url.indexOf('AsyncUpdateCart') >= 0 || url.indexOf('XcxGetOpenid') >= 0) {
        headers = {};
      }
      if (url.indexOf('XcxGetOpenid') < 0) {
        if (this.globalData.token){
          params.token = this.globalData.token;
          params.uid = this.globalData.uid;
          headers.Cookie = this.globalData.cookieKey;
        }
        else{
          this.getToken();
        }
      }
      let baseUrl = this.globalData.webUrl
      wx.request({
        url: baseUrl + url,
        header: headers,
        method: method.toUpperCase(),
        data: params,
        success: res => {
          if (res.statusCode === 200) {
            if (url.indexOf('XcxGetOpenid') >= 0) {
              if (parseInt(res.data.status) == 604){
                wx.redirectTo({
                  url: '/pages/blank/pageblankholder',
                });
              }
              else{
                if (res && res.header && res.header['Set-Cookie']) {
                  this.globalData.cookieKey = res.header['Set-Cookie'];
                }
                resolve(res.data);
              }
            }
            else{
              if (parseInt(res.data.status) == 400) {
                this.appReady = false;
                wx.login({
                  success: res => {
                    this.globalData.logincode = res.code;
                    this.getToken().then(() => {
                      this.request(url, params).then(res => { resolve(res) });
                    });
                  }
                });
              } else {
                resolve(res.data);
              }
            }
          } else {
            console.log(res);
            if (typeof res.data === 'object') {
              const errMsg = res.data.error || res.data.errMsg
                || res.data.errmsg || res.data.MSG || res.data.msg
                || res.data.message || '未知错误'
              reject(errMsg, res.statusCode, res.data)
            } else {
              reject(`请求发生异常, stauts:${res.statusCode}`)
            }
          }
        },
        fail: err => {
          reject('请检查网络连接')
        }
      })
    })
  },
  get: function (url, params) {
    return this.request(url, params, 'GET')
  },
  getPrevPage: function () {
    const pages = getCurrentPages()
    return pages[pages.length - 2]
  },
  formatDateTime: formatDateTime,
  isPhoneAvailable: isPhoneAvailable,
  toast: toast,
  confirm: confirm,
  showLoading: showLoading,
  hideLoading: hideLoading,
  showAddressModal: showAddressModal,
  ready: function (callback) {
    this.readyCallback = callback
    if (this.appReady) {
      this.dispatchReady()
    }
  },
  error: function (callback) {
    this.errorCallback = callback
    if (this.appError) {
      this.dispatchError()
    }
  },
  dispatchReady: function () {
    this.appReady = true
    if (typeof this.readyCallback === 'function') {
      this.readyCallback.apply(this, arguments)
      this.readyCallback = null
    }
  },
  dispatchError: function () {
    this.appError = true
    this.errMsg = arguments.length > 0
      ? [].slice.call(arguments)
      : this.errMsg
    if (typeof this.errorCallback === 'function') {
      this.errorCallback.apply(this, this.errMsg)
      this.errorCallback = null
    }
  },
  repicSrc: function (htmlmsg) {
    var str = htmlmsg;
    str = str.replace(/&(lt|gt|nbsp|amp|quot);/ig, function (all, t) { return arrEntities[t]; });
    if (str == "" || str == null)
      return;
    //匹配图片（g表示匹配所有结果i表示区分大小写）
    var imgReg = /<img.*?(?:>|\/>)/gi;
    //匹配src属性
    var srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i;
    var arr = str.match(imgReg);
    if (arr == null)
      return str;

    var keyArr = {};
    var i = 0;
    var src = '';
    for (i = 0; i < arr.length; i++) {
      src = arr[i].match(srcReg);
      if (src[1]) {
        keyArr[src[1]] = true;
      }
    }

    for (i = 0; i < arr.length; i++) {
      src = arr[i].match(srcReg);
      if (src[1]) {
        if (src[1].indexOf('http') < 0 && keyArr[src[1]]) {
          var regExp = new RegExp(src[1], "g");
          str = str.replace(regExp, this.globalData.webUrl + src[1]);
          keyArr[src[1]] = false;
        }
      }
    }

    return str;
  },
  // 保留两位小数
  keepTwoDecimalFull: function (num) {
    var result = parseFloat(num);
    result = Math.round(num * 100) / 100;
    var s_x = result.toString();
    var pos_decimal = s_x.indexOf('.');
    if (pos_decimal < 0) {
      pos_decimal = s_x.length;
      s_x += '.';
    }
    while (s_x.length <= pos_decimal + 2) {
      s_x += '0';
    }
    return s_x;
  },
  sendRuid: function () {
    if (!this.globalData.ruid){
      return;
    }
    var url = '/index.php/api/user/setRuid';
    var params = {
      ruid: this.globalData.ruid
    };
    this.request(url, params).then(res => {
      console.log(res);
    });
  },
  shareToIndex: function () {
    return {
      title: this.globalData.shareTitle,
      path: '/pages/newindex/newindex?scene=' + this.globalData.uid,
      imageUrl: this.globalData.shareImgUrl,
      success: (res) => {

      },
      fail: (res) => {

      }
    }
  },
  requestImage: function (imgurl) {
    return new Promise((resolve, reject) => {
      wx.getImageInfo({
        src: imgurl,
        success: (res) => {
          resolve(res);
        },
        fail: (err) => {
          reject('图片不存在');
        }
      });
    });
  }
})
